package gao.xiaolei.my_network_listener_plugin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import gao.xiaolei.my_network_listener_plugin.callback.NetworkChangeCallback;

public class NetworkListener extends BroadcastReceiver {
    private NetworkChangeCallback myNetworkChangeCallback;
    private ConnectivityManager connectivityManager;//本地网络管理

    public NetworkListener(NetworkChangeCallback myNetworkChangeCallback, ConnectivityManager connectivityManager) {
        this.myNetworkChangeCallback = myNetworkChangeCallback;
        this.connectivityManager = connectivityManager;
    }

    public NetworkListener() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {//监听网络变化
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable())
            this.myNetworkChangeCallback.networkChangeCallback(true);
        else
            this.myNetworkChangeCallback.networkChangeCallback(false);

    }

    public boolean currentNetworkIsAvailable(){//判断当前网络是否可用
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo != null&&networkInfo.isConnected())
            return true;
        return false;
    }
}
